import { BaseProps } from '../interface';
import CONFIG from '../config';

/*
 * @description Base 是所有其他类的父类
 * */
export default class Base {
  id: string;
  x: number;
  y: number;
  width: number;
  height: number;
  bgColor: string;
  canvas: HTMLCanvasElement;
  ctx: CanvasRenderingContext2D;

  /*
   * @constructor
   * id:图形的唯一标识
   * x:图形的x坐标
   * y:图形的y坐标
   * width:图形的宽度
   * height:图形的高度
   * bgColor:图形的背景颜色
   * */
  constructor(props: BaseProps) {
    this.id = props.id;
    this.x = props.x;
    this.y = props.y;
    this.width = props.width;
    this.height = props.height;
    this.bgColor = props.bgColor;
    this.canvas = document.getElementById(CONFIG.canvasId) as HTMLCanvasElement;
    this.ctx = this.canvas.getContext('2d') as CanvasRenderingContext2D;
  }

  /*
   * @return(number) 返回canvas的左坐标
   * */
  canvasLeft() {
    return this.canvas.getBoundingClientRect().left;
  }

  /*
   * @return(number) 返回canvas的右坐标
   * */
  canvasTop() {
    return this.canvas.getBoundingClientRect().top;
  }

  /*
   * @params(MouseEvent) 鼠标点击事件对象
   * @return({x:number,y:number}) 获取在canvas中的点击位置
   * */
  positionInCanvas(e: MouseEvent) {
    return {
      x: e.clientX - this.canvasLeft() + 1,
      y: e.clientY - this.canvasTop() + 1
    };
  }

  /*
   * @params(MouseEvent) 鼠标点击事件对象
   * @return(true/false) 获取鼠标是否点击了Canvas
   * */
  mousedownInCell(e: MouseEvent) {
    const { x, y } = this.positionInCanvas(e);

    return (
      x >= this.x &&
      x <= this.x + this.width &&
      y >= this.y &&
      y <= this.y + this.height
    );
  }

  /*
   * @params(fatherX) 父元素X坐标
   * @params(fatherY) 父元素Y坐标
   * @params(fatherWidth) 父元素宽度
   * @params(fatherHeight) 父元素高度
   * @params(childWidth) 子元素宽度
   * @params(childHeight) 子元素高度
   * @return({x:number,y:number}}) 居中后的坐标
   * */
  horizontalAndVerticalCenter(
    fatherX: number,
    fatherY: number,
    fatherWidth: number,
    fatherHeight: number,
    childWidth: number,
    childHeight: number
  ) {
    return {
      x: (fatherWidth - childWidth) / 2 + fatherX,
      y: (fatherHeight - childHeight) / 2 + fatherY
    };
  }

  /*
   * @params(fatherX) 父元素X坐标
   * @params(fatherWidth) 父元素宽度
   * @params(childWidth) 子元素宽度
   * @return(number) 居中后的水平坐标
   * */
  horizontalCenter(fatherX: number, fatherWidth: number, childWidth: number) {
    // return (fatherWidth - childWidth) / 2 + fatherX + 5;
    return (fatherWidth - childWidth) / 2 + fatherX;
  }
}